package com.winit.openapi.erp.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.order.OrderLineService;
import com.winit.erp.spi.order.command.CreateOrderLineCommand;
import com.winit.erp.spi.order.vo.OrderLine;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;

/**
 * @author ping.peng 2015-2-9 上午9:41:51
 * @since 1.0
 */
@Controller
@RequestMapping(value = "/fsp/order")
public class OrderLineController extends BaseController {

    @Resource
    private OrderLineService erpOrderLineService;

    @RequestMapping(value = "/createOrderLine")
    public String createOrderLine(@ModelAttribute RequestMsg requestMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            CreateOrderLineCommand command = buildCreateOrderLineCommand(json);
            erpOrderLineService.createOrderLine(command);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }

    private CreateOrderLineCommand buildCreateOrderLineCommand(JSONObject json) {
        CreateOrderLineCommand command = new CreateOrderLineCommand();
        command.setCtx(CommandContext.getContext());
        List<OrderLine> listOrderLine = new ArrayList<OrderLine>();
        JSONArray jsonList = json.getJSONArray("list");

        for (Object obj : jsonList.toArray()) {
            JSONObject jsonObj = (JSONObject) obj;
            OrderLine orderLine = new OrderLine();
            if (jsonObj.containsKey("orderId")) {
                orderLine.setOrderId(jsonObj.getLong("orderId"));
            }
            if (jsonObj.containsKey("bpartnerId")) {
                orderLine.setBpartnerId(jsonObj.getLong("bpartnerId"));
            }
            if (jsonObj.containsKey("warehouseId")) {
                orderLine.setWarehouseId(jsonObj.getLong("warehouseId"));
            }
            if (jsonObj.containsKey("productCode")) {
                orderLine.setProductCode(jsonObj.getString("productCode"));
            }
            if (jsonObj.containsKey("qtyEntered")) {
                orderLine.setQtyEntered(jsonObj.getBigDecimal("qtyEntered"));
            }
            listOrderLine.add(orderLine);
        }
        command.setListOrderLine(listOrderLine);

        return command;
    }

}
